package kz.simplex.photobox.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.ejb.Remove;
import javax.ejb.Stateful;

import kz.simplex.photobox.manager.IFileManager;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Stateful
@Name("imageLoader")
@Scope(ScopeType.EVENT)
@AutoCreate
public class ImageLoader implements IImageLoader {
	
	@In
	private IFileManager fileManager;
	
	public void paintImage(OutputStream out, Object data) throws IOException {
		if (data == null) {
			return;			
		}
		File imageResource = fileManager.getFileByPath(data.toString());
		paintImageToBrowser(out, imageResource);
	}
	
	
	public void paintAvatarImage(OutputStream out, Object data) throws IOException {
		if (data == null) {
			return;
		}		
		File imageResource = fileManager.getFileByPath(data.toString());
		if (imageResource == null || !imageResource.exists()) {
			imageResource = fileManager.getFileByAbsolutePath(data.toString());
		}
		paintImageToBrowser(out, imageResource);
	}
	
	private void paintImageToBrowser(OutputStream out, File imageResource) throws IOException {
		if (imageResource != null && imageResource.exists()) {
			byte[] a = new byte[8192];
			
			FileInputStream in = new FileInputStream(imageResource);
			
			try {
				while (in.read(a) != -1) {
					out.write(a);
				}
			} finally {
				in.close();
			}
		}
	}
	
	@Destroy
	@Remove
	public void destroy() {}
}
